<?php

namespace app\common\job;

use app\common\model\Trade;
use app\common\traits\JobRetryTraits;
use app\index\traits\PaymentTrait;
use think\queue\Job;

/**
 * 订单退款
 * Class TradeRefund
 * @package app\common\job
 */
class TradeRefund
{
    use PaymentTrait;
    use JobRetryTraits;

    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $id = $data['id'] ?? null;

        // 查询订单
        $record = Trade::field(true)->where('id', $id)->find();

        if ($record) {

            // 发起退款
            $result = $this->getPayment($record->payMethod)->refund($record);

            if (!$result) {
                $this->retryUntilMaxAttempts($job, 24, fn($attempts) => min($attempts, 3) * 3600, '消费队列：订单退款重试次数达到最大 ID' . $record->id);
                return;
            }
        }

        $job->delete();

    }

}
